package com.yinkgh.shiro;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/")
public class ShiroController {

	@RequestMapping("/tologin")
	public String toLogin() {
		return "shiro/login";
	}
	
	@RequestMapping("/login")
	public String doLogin(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("login dopost");
		String userName=req.getParameter("userName");
		String password=req.getParameter("password");
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(userName, password);
		try{
			subject.login(token);	
			Session session=subject.getSession();
			System.out.println("sessionId:"+session.getId());
			System.out.println("sessionHost:"+session.getHost());
			System.out.println("sessionTimeout:"+session.getTimeout());
			session.setAttribute("info", "session的数据");
		
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("用户名或者密码错误");
			req.setAttribute("errorInfo", "用户名或者密码错误");
//			req.getRequestDispatcher("/static/shiro/login.ftl").forward(req, resp);
			return "redirect:tologin";
		}
		return "redirect:success";
	}
	
	@RequestMapping("/success")
	public String toSuccess() {
		return "shiro/success";
	}
	
	
	
	
}

